//
//  AYSDatabaseHandle.m
//  AiYingShiProject
//
//  Created by lanou on 15/11/4.
//  Copyright (c) 2015年 李晓理. All rights reserved.
//

#import "AYSDatabaseHandle.h"

#import <sqlite3.h>

#import "AYSPlayDataModel.h"
#import "AYSFileHandle.h"
#import "AYSSmallListModel.h"
#define kVideoName @"AYSSmallDetailModel"
@implementation AYSDatabaseHandle

+ (instancetype)shareInstance
{
    static AYSDatabaseHandle *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[AYSDatabaseHandle alloc] init];
    });
    return handle;
}

static sqlite3 *db = nil;
// 打开数据库
- (void)openDB
{
    if (db != nil)
    {
        return;
    }
    
    // 数据库存储在沙河中的caches文件夹下
    NSString *dbPath = [[AYSFileHandle shareIntance] databaseFilepath:@"AiYingShi1.sqlite"];
    
    NSLog(@"da:%@",dbPath);
    // 打开数据库，第一个参数是数据库存储的完整路径
    // 如果数据库文件已经存在，是打开操作，如果数据库文件不存在，是先创建，再打开
    int result = sqlite3_open([dbPath UTF8String], &db);
    if (result == SQLITE_OK)
    {
        NSLog(@"打开数据库成功");
        // 创建表的数据库语句
        NSString *createSql = @"CREATE TABLE VideoList (ID TEXT PRIMARY KEY , title TEXT,  data BLOB);CREATE TABLE MovieList (ID INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT,  data BLOB)";
        // 执行sql语句
        sqlite3_exec(db, [createSql UTF8String], NULL, NULL, NULL);
    }
}

// 关闭数据库
- (void)closeDB
{
    int result = sqlite3_close(db);
    if (result == SQLITE_OK)
    {
        NSLog(@"关闭数据库成功");
        db = nil;
    }
}

// 添加新的电影
- (void)insertNewMovie:(AYSPlayDataModel *)movie
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"insert into MovieList(ID,title,data) values (?,?,?)";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK)
    {
        // 绑定
        sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%ld",[movie.programID integerValue]] UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [movie.programname UTF8String], -1, NULL);
        NSString *archiverKey = [NSString stringWithFormat:@"%@%@",@"AYSPlayDataModel",movie.programID];
        NSData *data = [[AYSFileHandle shareIntance] dataOfArchiverObject:movie forKey:archiverKey];
        sqlite3_bind_blob(stmt, 3, [data bytes], (int)[data length], NULL);
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
}

// 删除某个影片
- (void)deleteMovie:(AYSPlayDataModel *)movie
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"delete from MovieList where ID = ?";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK)
    {
        sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%ld",[movie.programID integerValue]] UTF8String], -1, NULL);
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
}

// 获取某个影片
- (AYSPlayDataModel *)selectMovieWithID:(NSNumber *)ID
{
    NSString *IDString = [NSString stringWithFormat:@"%ld", [ID integerValue]];
    
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select data from MovieList where ID = ?";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    
    AYSPlayDataModel *movie = nil;
    if (result == SQLITE_OK)
    {
        sqlite3_bind_text(stmt, 1, [IDString UTF8String], -1, NULL);
        if (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
            NSString *archiverKey = [NSString stringWithFormat:@"%@%@",@"AYSPlayDataModel",ID];
            movie = [[AYSFileHandle shareIntance] unarchiverObject:data forKey:archiverKey];
        }
    }
    sqlite3_finalize(stmt);
    return movie;
}

// 获取所有电影
- (NSArray *)selectAllMovie
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select ID,data from MovieList";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    NSMutableArray *movieArray = [NSMutableArray arrayWithCapacity:40];
    if (result == SQLITE_OK)
    {
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSString *ID = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 1) length:sqlite3_column_bytes(stmt, 1)];
            
            NSString *archiverKey = [NSString stringWithFormat:@"%@%@",@"AYSPlayDataModel",ID];
            AYSPlayDataModel *movie = [[AYSFileHandle shareIntance] unarchiverObject:data forKey:archiverKey];
            [movieArray addObject:movie];
        }
    }
    sqlite3_finalize(stmt);
    return movieArray;
}

// 判断对象是否被收藏
- (BOOL)isFavoriteMovieWithID:(NSNumber *)ID
{
    AYSPlayDataModel *m = [self selectMovieWithID:ID];
    if (m == nil)
    {
        return NO;
    }
    else
    {
        return YES;
    }
    
}

#pragma mark -----------收藏视频

// 添加新的视频
- (void)insertNewVideo:(AYSSmallListModel *)video
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"insert into VideoList(ID,title,data) values (?,?,?)";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK)
    {
        // 绑定
        sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%ld",[video.videoListID integerValue]] UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [video.title UTF8String], -1, NULL);
        NSString *archiverKey = [NSString stringWithFormat:@"%@%@",kVideoName,video.videoListID];
        NSData *data = [[AYSFileHandle shareIntance] dataOfArchiverObject:video forKey:archiverKey];
        sqlite3_bind_blob(stmt, 3, [data bytes], (int)[data length], NULL);
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
}

// 删除视频
- (void)deleteVideo:(AYSSmallListModel *)video
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"delete from VideoList where ID = ?";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    if (result == SQLITE_OK)
    {
        sqlite3_bind_text(stmt, 1, [[NSString stringWithFormat:@"%ld",[video.videoListID integerValue]] UTF8String], -1, NULL);
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
}

// 获取某个视频对象
- (AYSSmallListModel *)selectVideoWithID:(NSNumber *)ID
{
    NSString *IDString = [NSString stringWithFormat:@"%ld", [ID integerValue]];
    
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select data from VideoList where ID = ?";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    
    AYSSmallListModel *video = nil;
    if (result == SQLITE_OK)
    {
        sqlite3_bind_text(stmt, 1, [IDString UTF8String], -1, NULL);
        if (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 0) length:sqlite3_column_bytes(stmt, 0)];
            NSString *archiverKey = [NSString stringWithFormat:@"%@%@",kVideoName,ID];
            video = [[AYSFileHandle shareIntance] unarchiverObject:data forKey:archiverKey];
        }
    }
    sqlite3_finalize(stmt);
    return video;
}

// 获取所有视频
- (NSArray *)selectAllVideo
{
    [self openDB];
    sqlite3_stmt *stmt = nil;
    NSString *sql = @"select ID,data from VideoList";
    int result = sqlite3_prepare_v2(db, [sql UTF8String], -1, &stmt, NULL);
    NSMutableArray *videoArray = [NSMutableArray arrayWithCapacity:40];
    if (result == SQLITE_OK)
    {
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSString *ID = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            NSData *data = [NSData dataWithBytes:sqlite3_column_blob(stmt, 1) length:sqlite3_column_bytes(stmt, 1)];
            
            NSString *archiverKey = [NSString stringWithFormat:@"%@%@",kVideoName,ID];
            AYSSmallListModel *video = [[AYSFileHandle shareIntance] unarchiverObject:data forKey:archiverKey];
            [videoArray addObject:video];
        }
    }
    sqlite3_finalize(stmt);
    return videoArray;
}
// 判断视频是否被收藏
- (BOOL)isFavoriteVideoWithID:(NSNumber *)ID
{
    AYSSmallListModel *video = [self selectVideoWithID:ID];
    if (video == nil)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}





@end
